<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-card">
        <div class="login-header">
          <div class="logo">
            <img src="../assets/logo.svg" alt="Logo" />
          </div>
          <h1>欢迎登录</h1>
          <p>请输入您的账号信息</p>
        </div>

        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="username">用户名</label>
            <div class="input-wrapper">
              <input id="username" v-model="formData.username" type="text" placeholder="请输入用户名"
                :class="{ 'error': errors.username }" @blur="validateUsername" />
            </div>
            <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <div class="input-wrapper">
              <input id="password" v-model="formData.password" :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码" :class="{ 'error': errors.password }" @blur="validatePassword" />
              <button type="button" class="password-toggle" @click="togglePassword">
                {{ showPassword ? '隐藏' : '显示' }}
              </button>
            </div>
            <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
          </div>

          <div class="form-options">
            <label class="checkbox-wrapper">
              <input type="checkbox" v-model="formData.rememberMe" />
              记住密码
            </label>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>

          <button type="submit" class="login-button" :disabled="isLoading || !isFormValid">
            {{ isLoading ? '登录中...' : '登录' }}
          </button>

          <!-- <div class="register-link">
            还没有账号？<a href="#">立即注册</a>
          </div> -->
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import routerInfo from '@/router'
import auth from '@/api/modulesApi/auth'


const router = useRouter()

// 表单数据
const formData = reactive({
  username: 'admin',
  password: 'abcd1234',
  rememberMe: false
})

// 表单验证错误
const errors = reactive({
  username: '',
  password: ''
})

// 状态管理
const showPassword = ref(false)
const isLoading = ref(false)

// 计算属性：表单是否有效
const isFormValid = computed(() => {
  return formData.username.trim() && formData.password.trim() && !errors.username && !errors.password
})

// 验证用户名
const validateUsername = () => {
  const username = formData.username.trim()
  if (!username) {
    errors.username = '请输入用户名'
  } else if (username.length < 3) {
    errors.username = '用户名至少需要3个字符'
  } else {
    errors.username = ''
  }
}

// 验证密码
const validatePassword = () => {
  const password = formData.password
  if (!password) {
    errors.password = '请输入密码'
  } else if (password.length < 6) {
    errors.password = '密码至少需要6个字符'
  } else {
    errors.password = ''
  }
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 处理登录
const handleLogin = async () => {
  // 验证表单
  validateUsername()
  validatePassword()

  if (!isFormValid.value) {
    return
  }

  isLoading.value = true

  try {
    const res = await auth.login(formData)
    console.log(res)
    if (res.token) {
      localStorage.setItem('token', res.token)
      localStorage.setItem('router', JSON.stringify(res.routes))

      // 整理出菜单
      // const menu = data.routes.map(item => item.meta).filter(Boolean)
      const menuList = res.routes.reduce((acc, item) => {
        // item.meta存在null的情况
        if (!item.meta) {
          return acc
        }
        if (acc[item.meta.classEnName]) {
          let obj = { ...item.meta, moduleEnName: item.name }
          acc[item.meta.classEnName].push(obj)
        } else {
          let obj = { ...item.meta, moduleEnName: item.name }
          acc[item.meta.classEnName] = [obj]
        }
        return acc
      }, {})
      console.log('menuList', menuList)

      // console.log('menu', menu)
      // // 对classEnName字段进行分类保留重复的
      // const menuMap = menu.reduce((acc, item) => {
      //   if (acc[item.classEnName]) {
      //     acc[item.classEnName].push(item)
      //   } else {
      //     acc[item.classEnName] = [item]
      //   }
      //   return acc
      // }, {})
      // console.log('menuMap', menuMap)

      localStorage.setItem('menu', JSON.stringify(menuList))

      router.push('/')
    } else {
      throw new Error(res.message)
    }
  } catch (error) {
    // console.error('登录失败:', error)
    alert(error.message)
  } finally {
    isLoading.value = false
  }
}



// 获取记住密码
const getRememberPassword = () => {
  const rememberPassword = localStorage.getItem('rememberPassword')
  console.log('rememberPassword', rememberPassword)
  if (rememberPassword) {
    const savedData = JSON.parse(rememberPassword)
    formData.username = savedData.username
    formData.password = savedData.password
    formData.rememberMe = savedData.rememberMe
  }
}

// 初始化时获取保存的数据
getRememberPassword()

// 监听表单数据变化
watch(formData, () => {
  if (formData.rememberMe) {
    localStorage.setItem('rememberPassword', JSON.stringify(formData))
  } else {
    localStorage.removeItem('rememberPassword')
  }
}, { deep: true })

</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.login-background {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  max-width: 900px;
  margin: 0 auto;
  min-height: 600px;
}

.login-header {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.logo {
  margin-bottom: 30px;
}

.logo img {
  width: 80px;
  height: 80px;
  filter: brightness(0) invert(1);
}

.login-header h1 {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 10px 0;
  letter-spacing: -0.5px;
}

.login-header p {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.login-form {
  flex: 1;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  font-size: 0.9rem;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper input {
  width: 100%;
  padding: 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.input-wrapper input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-wrapper input.error {
  border-color: #e74c3c;
}

.password-toggle {
  position: absolute;
  right: 16px;
  background: none;
  border: none;
  cursor: pointer;
  color: #667eea;
  font-size: 0.9rem;
}

.error-message {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 6px;
  display: block;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 0.9rem;
  color: #666;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-size: 0.9rem;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.register-link {
  text-align: center;
  font-size: 0.9rem;
  color: #666;
}

.register-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
}

.register-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    flex-direction: column;
    max-width: 400px;
  }

  .login-header {
    padding: 40px 20px;
  }

  .login-form {
    padding: 40px 20px;
  }

  .form-options {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .login-background {
    padding: 10px;
  }

  .login-header h1 {
    font-size: 2rem;
  }

  .login-header p {
    font-size: 1rem;
  }
}
</style>
